package com.bobo.job;


import com.bobo.common.constant.URLConstant;
import com.bobo.util.ImageDowloader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Description: 图片定时任务
 * @Auther: Swain
 * @Date: 2021/1/8 10:26
 * @Version 1.0.0
 */
@Component
public class ImageJob {

    private Logger logger = LoggerFactory.getLogger(ImageJob.class);

    public static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static final String url = URLConstant.BEAUTY_URL;

    //5s执行一次
    @Scheduled(cron = "*/5 * * * * ?")
    public void catchImages() {

        try {
            String rootPath = System.getProperty("user.dir") + File.separator + "data" + File.separator + "image";
            String filePath = ImageDowloader.getCurrentDateTime("yyyyMMdd");
            File fileImage = new File(rootPath + File.separator + filePath);
            if (!fileImage.exists()) {
                fileImage.mkdirs();
            }
            String fileName = File.separator + "bobo" + new Date().getTime() + ".jpg";

            String finlPath = rootPath + File.separator + filePath + fileName;

            ImageDowloader.dowloadImage(url, finlPath);
            logger.info("Crawl is successful, the image address is:" + finlPath);
        } catch (Exception e) {
            logger.error(format.format(new Date()) + "\n" +
                    "Crawl failed, the error message is:", e);
        }
    }

}
